from rest_framework import serializers
from django.db.models import Q,Avg

from .models import MovieDetail, MovieCountry, MovieStaff, MovieStaffCategory, MovieKindCategory, \
    MovieTypeCategory,FilmSchedule,TicketSeat,MovieHallSeat

from user_movies_operations.models import UserWantMovie,UserStarMovie


class KindCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = MovieKindCategory
        fields = ('name', 'id')


class MovieStaffSerializer(serializers.ModelSerializer):
    class Meta:
        model = MovieStaff
        fields = "__all__"


class MovieCountrySerializer(serializers.ModelSerializer):
    class Meta:
        model = MovieCountry
        fields = "__all__"


class MovieTypeCategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = MovieTypeCategory
        fields = "__all__"


class MovieInfoDetailSerializer(serializers.ModelSerializer):
    # 序列化里面的嵌套循环 如果是对多对模型就需要设置 many=True,read_only=True一般要写上
    kind_category = KindCategorySerializer(many=True, read_only=True)
    movie_state = MovieCountrySerializer(many=True, read_only=True)
    staffs = MovieStaffSerializer(many=True, read_only=True)
    type_category = MovieTypeCategorySerializer(many=True, read_only=True)
    wanted_num = serializers.SerializerMethodField(read_only=True)
    avg_star = serializers.SerializerMethodField(read_only=True)

    def get_wanted_num(self, obj):

        return UserWantMovie.objects.filter(movie=obj).count()

    def get_avg_star(self,ins):

        data = UserStarMovie.objects.filter(movie=ins).aggregate(Avg('star'))
        score = data.get('star__avg')
        score = round(score,1)
        return score

    class Meta:
        model = MovieDetail
        fields = "__all__"


class MovieInfoListSerializer(serializers.ModelSerializer):
    # 序列化里面的嵌套循环 如果是对多对模型就需要设置 many=True,read_only=True一般要写上

    type_category = MovieTypeCategorySerializer(many=True, read_only=True)

    class Meta:
        model = MovieDetail
        fields = "__all__"


class MovieHallSeatSeatSerializer(serializers.ModelSerializer):

    class Meta:
        model = MovieHallSeat
        fields = "__all__"


class TicketSeatSerializer(serializers.ModelSerializer):
    movie_hall_seat = MovieHallSeatSeatSerializer(read_only=True)
    class Meta:
        model = TicketSeat
        fields = "__all__"

class FilmScheduleSerializer(serializers.ModelSerializer):
    # 序列化里面的嵌套循环 如果是对多对模型就需要设置 many=True,read_only=True一般要写上

    ticket_seat_film = TicketSeatSerializer(read_only=True,many=True)

    class Meta:
        model = FilmSchedule
        fields = "__all__"
